<template>
<div>
    <vxe-table class="flowStepTable" :data="tableData" ref="tableRef" border height="100%" :scroll-y="{enabled: false}"
        :span-method="mergeCells" :cell-class-name="addCellClassName">
        <vxe-column field="taskName" title="审批步骤" min-width="120" show-overflow-tooltip>
            <template v-slot="{ row }">
                <div>
                    <span class="text-bold">{{ row.taskName }}</span>
                    <svg-icon class="myIcon" name="risk-taskRisk" width="14px" height="14px" color='var(--el-color-danger)' @click="clickRisk(row.taskRisks)" v-if="row.taskRisks && row.taskRisks.length>0"/>
                    <span class="text-danger text-bold" v-if="row.dictSpeAuditType==='2'">&nbsp;会签</span>
                </div>
                <div class="text-danger m-t-xs text-bold">
                    <!-- 审批状态 -->
                    <span v-if="row.dictSpeAuditStatus==='1'">处理中</span>
                    <span v-else-if="row.dictSpeAuditStatus==='3'">已终止</span>
                </div>
            </template>
        </vxe-column>
        <vxe-column field="startTime" title="开始时间" min-width="120" align="center" show-overflow-tooltip></vxe-column>
        <vxe-column field="auditUserName" title="审核人" min-width="160" show-overflow-tooltip>
            <template v-slot="{ row }">
                <div class="inline-block" v-if="row.auditUserName">
                    <span v-if="row.auditUserName == row.candidateUserName">
                        <span>{{ row.auditUserName }}</span>
                    </span>
                    <span v-if="row.auditUserName != row.candidateUserName">
                        <span class="text-primary">{{ row.auditUserName }}</span>
                        <span class="text-success">【代理{{ row.candidateUserName }}】</span>
                    </span>
                </div>
                <div class="inline-block" v-else>
                    <span>{{ row.candidateUserName?row.candidateUserName:'--' }}</span>
                </div>
                <el-tooltip v-if="row.isAddCountersign===1" :content="`【${row.createdUserName}添加会签人】`" placement="bottom">
                    <span class="huiIcon">会</span>
                </el-tooltip>
            </template>
        </vxe-column>
        <vxe-column field="auditTime" title="审核时间" min-width="120" align="center" show-overflow-tooltip></vxe-column>
        <vxe-column field="opinion" title="审核意见" min-width="260" show-overflow-tooltip>
            <template v-slot="{ row }">
                <span :class="[{'text-success': row.action=='同意'},{'text-danger': row.action=='退回'},{'text-primary': row.action=='提交'},'text-bold']">{{ row.action }}</span> 
                <div class="inline-block m-l-xs" v-if="row.opinion">{{ row.opinion }}</div>
                <div class="inline-block m-l-xs" v-if="row.fileList.length>0">
                    <el-popover placement="right" :width="400" trigger="click">
                        <template #reference>
                            <svg-icon name="file" color=var(--el-color-primary-dark-2) width="16px" height="16px" style="position: relative; top:3px;"></svg-icon>
                        </template>
                        <ul>
                            <li class="m-b-sm" v-for="(item, index) in row.fileList" :key="index" :title="item.name" @click="downloadFile(item)" >
                                附件{{ index+1 }}：<a href="javascript:;">{{item.name}}</a>
                            </li>
                        </ul>
                    </el-popover>
                </div>
            </template>
        </vxe-column>
    </vxe-table>
    <risk-dig :taskRisks="taskRisks" v-if="isRiskVisible" @closeDig="isRiskVisible=false"></risk-dig>
</div>
</template>

<script setup lang="ts">
import flowApi from '@/api/flow/index.ts';
import RiskDig from '@/components/flow/flowStepRisk.vue';
import fileApi from '@/api/file/file.ts';
import { handleExportData } from '@/utils/public';

const props = defineProps({
    procInstanceId: {
        type: [Number, String],
        default: null
    }
})

const proId = ref<number | string>('');

watch(() => props.procInstanceId, (val: any) => {
    proId.value = val;
    getStepList()
})

onMounted(() => {
    proId.value = props.procInstanceId;
    getStepList()
})

const tableData = ref<any[]>([]);
const loading = ref(false);

const getStepList = async () => {
    try {
        loading.value = true;
        let results = await flowApi.getWorkflowStep(proId.value) as any;
        if (results) {
            // 接口调用成功
            tableData.value = [];
            // 添加: 为每组数据添加 groupKey
            results.forEach((itemA: any, index: number) => {
                if(itemA.taskAudits.length>0){
                    itemA.taskAudits.forEach((itemB: any) => {
                        tableData.value.push({
                            taskName: itemA.taskName,
                            dictSpeAuditStatus:  itemA.dictSpeAuditStatus,
                            startTime: itemA.startTime,
                            taskRisks: itemA.taskRisks,
                            dictSpeAuditType: itemA.dictSpeAuditType,
                            auditUserName: itemB.auditUserName,  // 审核人姓名
                            candidateUserName: itemB.candidateUserName, //待审批人姓名
                            auditTime: itemB.auditTime,
                            action: itemB.action,
                            opinion: itemB.opinion,
                            isAddCountersign: itemB.isAddCountersign,
                            createdUserName: itemB.createdUserName,
                            fileList: itemB.fileList,
                            // 添加: groupKey 用于标识每组数据
                            groupKey: index,
                            popoverVisible: false // 添加独立控制popover显示的属性
                        })
                    })
                }
            })
        } else {
            // 处理接口调用成功，但返回结果为空的情况
            throw new Error("接口调用成功，但返回结果为空");
        }
    } catch (error) {
        // 处理接口调用失败的情况
        throw new Error("接口调用失败"); // 返回一个默认值或者进行其他错误处理
    } finally {
        loading.value = false;
    }
};

// 添加单元格合并逻辑
const mergeCells = ({ row, column, visibleData }: any) => {
    const fields = ['taskName', 'startTime'];
    if (fields.includes(column.property)) {
        const groupKey = row.groupKey; // 使用 groupKey 进行分组判断
        if (groupKey === null || groupKey === undefined) {
            return { rowspan: 1, colspan: 1 };
        }

        let rowspan = 1;
        let currentIndex = visibleData.indexOf(row);

        // 向上查找相同 groupKey 的行
        while (currentIndex > 0) {
            const prevRow = visibleData[currentIndex - 1];
            if (prevRow.groupKey === groupKey) {
                currentIndex--;
            } else {
                break;
            }
        }

        // 如果当前行不是第一个相同 groupKey 的行，则返回 rowspan: 0, colspan: 0 隐藏单元格
        if (visibleData.indexOf(row) !== currentIndex) {
            return { rowspan: 0, colspan: 0 };
        }

        // 向下计算相同 groupKey 的行数
        while (currentIndex + rowspan < visibleData.length) {
            const nextRow = visibleData[currentIndex + rowspan];
            if (nextRow.groupKey === groupKey) {
                rowspan++;
            } else {
                break;
            }
        }
        return { rowspan, colspan: 1 };
    }

    return { rowspan: 1, colspan: 1 };
};

// 重构 addCellClassName 函数以正确识别每组的最后一行单元格, 添加单元格类名
const addCellClassName = ({ row, rowIndex, column }:any) => {
    const visibleData = tableData.value;
    const fields = ['taskName', 'startTime'];
    if (fields.includes(column.property)) {
        return 'cell-group-last';
    }
    // 检查当前行是否为组的最后一行
    if (rowIndex < visibleData.length - 1) {
        const nextRow = visibleData[rowIndex + 1];

        // 如果下一行的 groupKey 不同，说明当前行是组的最后一行
        if (nextRow && nextRow.groupKey !== row.groupKey) {
            return 'cell-group-last';
        }
    } else {
        // 数据的最后一行也视为组的最后一行
        return 'cell-group-last';
    }
    return '';
};
const taskRisks = ref([]);
const isRiskVisible = ref(false);

const clickRisk = ( val: any) => {
    taskRisks.value = val;
    isRiskVisible.value = true;
};
const downloadFile = async (item:any) => {
    showLoading();
    try {
		const res = await fileApi.downloadById({
			"id": item.id
        }) as unknown as any;
		handleExportData(res, item.name)		
	}  catch (error) {
		throw new Error("接口调用失败"); 
	} finally {
		hideLoading();
	}
}
</script>
<style lang="scss" scoped>
.huiIcon{ display: inline-block; width: 16px; text-align: center; height: 16px; line-height: 16px; border-radius: 50%; background: var(--el-color-danger); color: #fff; margin-left: 5px;}
.myIcon{ display: inline-block; position: relative; top: -2px; margin-left: 3px;}

// 为每组的最后一行添加黑色2px下边框
:deep(.flowStepTable) .vxe-body--row td.cell-group-last {
    border-bottom: 1px solid var(--el-border-color);
}
// 添加垂直居中样式
:deep(.flowStepTable) .vxe-body--row td {
    vertical-align: middle;
}
:deep(.poverTable) .vxe-body--row td {
    vertical-align: middle;
}
</style>
